/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package gui;

import interfaces.EditPanel;

import java.awt.Dimension;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import tools.InputType;
import tools.StringTools;
import botobjects.User;
import database.DBConnectionFactory;

/**
 * Settings panel for users
 * 
 * 
 */
public class UsersPanel extends JPanel implements EditPanel {
   private static final long serialVersionUID = 4228896307757033356L;
   private JTextField mainNick;
   private JTextField realName;
   private JTextField country;
   private JTextField timeZone;
   private JTextField sms;
   private JTextArea misc;
   private JCheckBox isAdmin;
   private final DialogPanel parent;

   public UsersPanel(final DialogPanel parent) {
	  super();
	  this.parent = parent;
	  initialize();
   }

   @Override
   public final void checkInputs() {
	  if (mainNick.getText().equals("") || !StringTools.validateInput(InputType.INT, timeZone.getText())) {
		 parent.setSaveButtonEnabled(false);
	  } else {
		 parent.setSaveButtonEnabled(true);
	  }
   }

   @Override
   public boolean delete() {
	  if (mainNick.getText().equals(""))
		 return false;
	  PreparedStatement ps = null;
	  boolean success = false;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("DELETE FROM kdmember WHERE mainnick = ?");
		 ps.setString(1, mainNick.getText());
		 ps.executeUpdate();
		 success = true;
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return success;
   }

   @Override
   public String getItemName() {
	  return mainNick.getText();
   }

   /**
    * Initializes the components
    */
   private void initialize() {
	  setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
	  setMaximumSize(new Dimension(300, 180));
	  mainNick = new JTextField();
	  mainNick.setPreferredSize(new Dimension(200, 20));
	  mainNick.setEditable(false);
	  realName = new JTextField();
	  realName.setPreferredSize(new Dimension(200, 20));
	  realName.getDocument().addDocumentListener(new MyDocumentListener(this));
	  country = new JTextField();
	  country.setPreferredSize(new Dimension(200, 20));
	  country.getDocument().addDocumentListener(new MyDocumentListener(this));
	  timeZone = new JTextField();
	  timeZone.setPreferredSize(new Dimension(200, 20));
	  timeZone.getDocument().addDocumentListener(new MyDocumentListener(this));
	  misc = new JTextArea();
	  misc.setRows(5);
	  misc.setPreferredSize(new Dimension(200, 20));
	  misc.setLineWrap(true);
	  misc.getDocument().addDocumentListener(new MyDocumentListener(this));
	  sms = new JTextField();
	  sms.setPreferredSize(new Dimension(200, 20));
	  sms.getDocument().addDocumentListener(new MyDocumentListener(this));
	  isAdmin = new JCheckBox("Select for yes");
	  isAdmin.addChangeListener(new javax.swing.event.ChangeListener() {
		 @Override
		 public void stateChanged(final javax.swing.event.ChangeEvent e) {
			checkInputs();
		 }
	  });

	  this.add(new CustomPanel(new CustomLabel("Main Nick", 80, 20), mainNick));
	  this.add(new CustomPanel(new CustomLabel("Real Name", 80, 20), realName));
	  this.add(new CustomPanel(new CustomLabel("Country", 80, 20), country));
	  this.add(new CustomPanel(new CustomLabel("Time Zone", 80, 20), timeZone));
	  this.add(new CustomPanel(new CustomLabel("Misc", 80, 20), misc));
	  this.add(new CustomPanel(new CustomLabel("SMS Address", 80, 20), sms));
	  this.add(new CustomPanel(new CustomLabel("Admin", 80, 20), isAdmin));
   }

   @Override
   public JPanel load(final String item) {
	  removeAll();
	  validate();
	  initialize();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM kdmember WHERE kdmember.mainnick = ?");
		 ps.setString(1, item);
		 rs = ps.executeQuery();

		 if (rs.next()) {
			mainNick.setText(rs.getString("kdmember.mainnick"));
			realName.setText(rs.getString("realname"));
			country.setText(rs.getString("country"));
			timeZone.setText(String.valueOf(rs.getInt("timezone")));
			misc.setText(rs.getString("misc").replace('\t', ' '));

			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM sms WHERE nick = ?");
			ps.setString(1, item);
			rs = ps.executeQuery();

			if (rs.next()) {
			   sms.setText(rs.getString("mail"));
			}

			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("SELECT * FROM admins WHERE mainnick = ?");
			ps.setString(1, item);
			rs = ps.executeQuery();

			if (rs.next()) {
			   isAdmin.setSelected(true);
			}
		 } else {
			mainNick.setText(item);
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return this;
   }

   public JPanel loadEmpty(final String item) {
	  removeAll();
	  validate();
	  initialize();
	  mainNick.setText(item);
	  return this;
   }

   @Override
   public boolean save() {
	  if (mainNick.getText().equals("") || !StringTools.validateInput(InputType.INT, timeZone.getText()))
		 return false;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  boolean success = false;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM kdmember WHERE mainnick = ?");
		 ps.setString(1, mainNick.getText());
		 rs = ps.executeQuery();

		 if (rs.next()) {
			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("UPDATE kdmember SET " + "realname = ?,country = ?,timezone = ?,misc =? WHERE mainnick = ?");
			ps.setString(1, realName.getText());
			ps.setString(2, country.getText());
			ps.setInt(3, Integer.parseInt(timeZone.getText()));
			String[] split = misc.getText().split("\n");
			String newMisc = "";
			for (String s : split) {
			   if (!"".equals(s)) {
				  String type = s.substring(0, s.indexOf(' ')).trim();
				  String contact = s.substring(s.indexOf(' ')).trim();
				  newMisc += type + "\t" + contact + "\n";
			   }
			}
			ps.setString(4, newMisc);
			ps.setString(5, mainNick.getText());
			ps.executeUpdate();

			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("UPDATE sms SET mail = ? WHERE nick = ?");
			ps.setString(1, sms.getText());
			ps.setString(2, mainNick.getText());
			ps.executeUpdate();
		 } else {
			try {
			   ps.close();
			} catch (final Exception e) {
			}

			if (!new User(mainNick.getText()).saveToDB())
			   throw new SQLException("Couldn't save user");

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("UPDATE kdmember SET realname = ?,country = ?,timezone = ?,misc = ? WHERE mainnick = ?");
			ps.setString(1, realName.getText());
			ps.setString(2, country.getText());
			ps.setInt(3, Integer.parseInt(timeZone.getText()));
			String[] split = misc.getText().split("\n");
			String newMisc = "";
			for (String s : split) {
			   if (!"".equals(s)) {
				  String type = s.substring(0, s.indexOf(' ')).trim();
				  String contact = s.substring(s.indexOf(' ')).trim();
				  newMisc += type + "\t" + contact + "\n";
			   }
			}
			ps.setString(4, newMisc);
			ps.setString(5, mainNick.getText());
			ps.executeUpdate();

			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("INSERT INTO sms VALUES(?,?,false)");
			ps.setString(1, mainNick.getText());
			ps.setString(2, sms.getText());
			ps.executeUpdate();
		 }

		 try {
			ps.close();
		 } catch (final Exception e) {
		 }

		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM admins WHERE mainnick = ?");
		 ps.setString(1, mainNick.getText());
		 rs = ps.executeQuery();

		 if (rs.next()) {
			if (!isAdmin.isSelected()) {
			   try {
				  ps.close();
			   } catch (final Exception e) {
			   }

			   ps = DBConnectionFactory.getConnectionHandler().getConnection()
					 .prepareStatement("DELETE FROM admins WHERE mainnick = ?");
			   ps.setString(1, mainNick.getText());
			   ps.executeUpdate();
			}
		 } else {
			if (isAdmin.isSelected()) {
			   try {
				  ps.close();
			   } catch (final Exception e) {
			   }

			   ps = DBConnectionFactory.getConnectionHandler().getConnection()
					 .prepareStatement("INSERT INTO admins VALUES(?,false)");
			   ps.setString(1, mainNick.getText());
			   ps.executeUpdate();
			}
		 }
		 success = true;
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return success;
   }
}
